import React, { useState, useEffect } from 'react';
import { GlobalStyles } from '@mui/material';

/**
 * Enhanced DiagonalImageSlice with dual background images
 * One for the page background and one for the diagonal slice
 * Added backgroundCover prop to control background sizing
 * Added visibility prop to control whether the background is visible
 */
const BodyDiagonalImageSlice = ({
  // Diagonal slice image
  sliceImage,
  // Full page background image
  backgroundImage,
  // Whether to use cover for background image (true) or natural size (false)
  backgroundCover = false,
  // Option to enable the diagonal slice (disabled by default)
  showSlice = false,
  // Option to enable the background (disabled by default)
  visible = false,
  // Size of the diagonal
  thickness = 500,
  // Animation factors
  sliceZoomFactor = 2,
  backgroundZoomFactor = 1.5,
  shiftIntensity = 5,
  duration = 0.5,
  // Styling options
  hasBorder = false,
  borderColor = '#000',
  hasInnerShadow = false,
  shadowColor = 'rgba(0,0,0,0.5)',
  shadowIntensity = 0,
  children
}) => {
  const [isScrolling, setIsScrolling] = useState(false);
  
  // Detect scrolling start/stop
  useEffect(() => {
    let timeout;
    const onScroll = () => {
      if (!isScrolling) setIsScrolling(true);
      clearTimeout(timeout);
      timeout = setTimeout(() => setIsScrolling(false), 150);
    };
    
    window.addEventListener('scroll', onScroll, { passive: true });
    
    // Add a class to the body when component mounts
    document.body.classList.add('has-diagonal-slice');
    
    return () => {
      window.removeEventListener('scroll', onScroll);
      clearTimeout(timeout);
      
      // Clean up body classes when component unmounts
      document.body.classList.remove('has-diagonal-slice');
      document.body.classList.remove('is-scrolling');
    };
  }, [isScrolling]);
  
  // Update body class based on scrolling state
  useEffect(() => {
    if (isScrolling) {
      document.body.classList.add('is-scrolling');
    } else {
      document.body.classList.remove('is-scrolling');
    }
  }, [isScrolling]);
  
  // Calculate shadow based on intensity
  const shadowValue = hasInnerShadow 
    ? `inset 0 0 ${shadowIntensity * 5}px ${shadowIntensity * 2}px ${shadowColor}`
    : 'none';
  
  // Calculate border
  const borderValue = hasBorder ? `2px solid ${borderColor}` : 'none';
  
  // Calculate shift offsets when scrolling
  const shiftOffset = thickness * (shiftIntensity / 20);
  
  // Only render if visible is true
  if (!visible) {
    return <>{children}</>;
  }
  
  return (
    <>
      <GlobalStyles 
        styles={{
          // General setup for the body with diagonal slice
          'body.has-diagonal-slice': {
            position: 'relative',
            overflow: 'auto',
          },
          
          // Full page background
          'body.has-diagonal-slice::after': {
            content: '""',
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100vw',
            height: '100vh',
            zIndex: -2, // Below the diagonal slice
            backgroundImage: backgroundImage ? `url(${backgroundImage})` : 'none',
            backgroundSize: backgroundCover ? 'cover' : 'auto',
            backgroundPosition: 'center',
            backgroundRepeat: backgroundCover ? 'no-repeat' : 'no-repeat',
            transition: `transform ${duration}s ease-out`,
            transform: 'scale(1)',
            transformOrigin: 'center center',
            willChange: 'transform',
            backfaceVisibility: 'hidden',
            perspective: 1000,
          },
          
          // Background zoom effect when scrolling
          'body.has-diagonal-slice.is-scrolling::after': {
            transform: `scale(${backgroundZoomFactor})`,
          },
          
          // Diagonal slice with its own background
          'body.has-diagonal-slice::before': {
            content: '""',
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100vw',
            height: '100vh',
            zIndex: -1, // Above the full background
            clipPath: showSlice ? `polygon(
              0 ${thickness}px,
              100% 0,
              100% calc(100% - ${thickness}px),
              0 100%
            )` : 'none',
            backgroundImage: (showSlice && sliceImage) ? `url(${sliceImage})` : 'none',
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            border: borderValue,
            boxShadow: shadowValue,
            transition: `transform ${duration}s ease-out`,
            transform: 'translate(0, 0) scale(1)',
            transformOrigin: 'center center',
            willChange: 'transform',
            backfaceVisibility: 'hidden',
            perspective: 1000,
            '-webkit-font-smoothing': 'subpixel-antialiased'
          },
          
          // Diagonal slice transformations during scrolling
          'body.has-diagonal-slice.is-scrolling::before': {
            transform: showSlice ? `translate(${-shiftOffset}px, ${-shiftOffset}px) scale(${sliceZoomFactor})` : 'none',
          }
        }}
      />
      
      {/* Children rendered on top */}
      {children}
    </>
  );
};

export default BodyDiagonalImageSlice;